package com.lc.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.reggie.dao.CategoryMapper;
import com.lc.reggie.entity.Category;
import com.lc.reggie.entity.Dish;
import com.lc.reggie.entity.Setmeal;
import com.lc.reggie.service.CategoryService;
import com.lc.reggie.service.DishService;
import com.lc.reggie.service.SetmealService;
import com.lc.reggie.common.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService
{
	@Autowired
	private DishService dishService;
	
	@Autowired
	private SetmealService setmealService;
	
	/**
	 * 根据id删除分类，删除之前需要进行判断
	 * @param id
	 */
	@Override
	public void remove(Long id)
	{
		Category category = super.getById(id);
		Integer type = category.getType();
		
		if (type == 1)
		{
			LambdaQueryWrapper<Dish> dishLqw = new LambdaQueryWrapper<>();
			//添加查询条件，根据分类id来查询
			dishLqw.eq(Dish::getCategoryId, id);
			int dishCount = dishService.count(dishLqw);
			
			//查询当前分类是否关联了菜品，如果已经关联抛出一个业务异常
			if (dishCount > 0)
			{
				//已经关联菜品，抛出一个业务异常
				throw new CustomException("当前分类下关联了菜品，不能删除");
			}
		}
		else
		{
			LambdaQueryWrapper<Setmeal> setMealLqw = new LambdaQueryWrapper<>();
			//添加查询条件，根据分类id来查询
			setMealLqw.eq(Setmeal::getCategoryId, id);
			int setMealCount = setmealService.count(setMealLqw);
			
			//查询当前分类是否关联了套餐，如果已经关联抛出一个业务异常
			if (setMealCount > 0)
			{
				//已经关联套餐，抛出一个业务异常
				throw new CustomException("当前分类下关联了套餐，不能删除");
			}
		}
		
		//正常删除分类
		super.removeById(id);
	}
}
